package com.itheima.ydd.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.HashUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.YddArticleDto;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.entity.YddUserData;

import com.itheima.ydd.entity.*;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.mapper.YddArticleMapper;
import com.itheima.ydd.service.ISysDictService;
import com.itheima.ydd.service.IYddArticleService;
import com.itheima.ydd.service.IYddCateService;
import com.itheima.ydd.service.IYddUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Service
@Slf4j
public class YddArticleServiceImpl extends ServiceImpl<YddArticleMapper, YddArticle> implements IYddArticleService {
    @Autowired
    private IYddArticleService iYddArticleService;
    @Autowired
    private IYddCateService iYddCateService;

    @Autowired
    private ISysDictService iSysDictService;
//    @Autowired
//    private IYddCateService iYddCateService;
    @Autowired
    private IYddUserService yddUserService;

    /**
     * 我的文章
     *
     * @param limit
     * @param page
     * @return
     */
    @Override
    public ResultData myArticle(Integer limit, Integer page,HttpServletRequest request) {
        //分页查询
        Integer limits = Integer.valueOf(limit);
        Integer pages = Integer.valueOf(page);
        Page ipage = new Page(pages,limits);
        ipage = page(ipage);
        Map<Object, Object> map = new HashMap<>();
        map.put("count", ipage.getTotal());
        map.put("totalPages", limits);
        map.put("pageSize", ipage.getSize());
        map.put("currentPage", ipage.getCurrent());
        map.put("data", ipage.getRecords());

        return ResultData.ok("查询成功", map);
    }

    /**
     * 修改文章
     *
     * @param yddArticle
     * @return
     */
    @Override
    public ResultData editArticle(YddArticle yddArticle) {
        Date date = new Date();
        yddArticle.setUpdateDate(date.getTime());
        log.info(yddArticle.getCreateDate() + "");
        updateById(yddArticle);
        return ResultData.ok("修改成功", null);
    }

    /**
     * 发布文章
     *
     * @param yddArticle
     * @return
     */
    @Override
    public ResultData addArticle(YddArticle yddArticle, HttpServletRequest request) {
        String userId = request.getHeader("token");
        yddArticle.setUserId(Integer.parseInt(userId));
        yddArticle.setLovenum("0");
        Date date = new Date();
        yddArticle.setCreateDate(date.getTime());
        save(yddArticle);
        return ResultData.ok("发布成功", null);
    }

    @Override
    public ResultData getByList(List<YddUserData> list, Integer page, Integer limit) {
        Page<YddArticle> page1 = new Page<>(page, limit);
        ArrayList<Object> objects = new ArrayList<>();
        for (YddUserData yddUserData : list) {
            objects.add(yddUserData.getArticleId());
        }

        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(YddArticle::getId, objects);
        Page<YddArticle> page2 = page(page1, wrapper);

        List<Object> objects1 = new ArrayList<>();

        page2.getRecords().stream().map((item) -> {
//            YddArticleDto yddArticleDto = new YddArticleDto();
//            BeanUtils.copyProperties(item, yddArticleDto);
//            Integer cateid = item.getCateid();
            YddCate byId1 = iYddCateService.getById(item.getCateid());
            String catename = byId1.getCatename();
            HashMap<Object, Object> map = new HashMap<>();
            map.put("author",item.getAuthor());
            map.put("catename",catename);
            map.put("click",item.getClick());
            map.put("create_date",item.getCreateDate());
            map.put("description",item.getDescription());
            map.put("id",item.getId());
            map.put("ishot",item.getIshot());
            map.put("istop",item.getIstop());
            map.put("keywords",item.getKeywords());
            map.put("lovenum",item.getLovenum());
            map.put("pic",item.getPic());
            map.put("yags",item.getTags());
            map.put("title",item.getTitle());
            objects1.add(map);
            return item;
        }).collect(Collectors.toList());

        HashMap<Object, Object> map = new HashMap<>();
        map.put("count",page2.getCountId());
        map.put("totalPages",page2.getTotal());
        map.put("pageSize",page2.getSize());
        map.put("currentPage",page2.getCurrent());
        map.put("data",objects1);

        HashMap<Object, Object> map2 = new HashMap<>();
        map2.put("list",map);

        return ResultData.ok("操作成功", map2);
    }

    @Override
    public Integer getarticle(Integer id) {
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddArticle::getUserId, id);
        List<YddArticle> list = list(wrapper);
        return list.size();
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResultData delArticle(String id) {
        Integer integer = Integer.valueOf(id);
        removeById(integer);
        return ResultData.ok("删除成功", null);
    }

    /**
     * 文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResultData show(String id) {
        Map<Object, Object> map = new HashMap<>();
        YddArticle nextArticle = new YddArticle();
        YddArticle prevArticle = new YddArticle();
        Integer ArticleId = Integer.valueOf(id);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        //上一篇数据
        int prevId = ArticleId - 1;
        YddArticle prevById = getById(prevId);
        if (prevById==null){
            map.put("prev", null);
        }else {
            String prevTitle = prevById.getTitle();
            prevArticle.setId(prevId);
            prevArticle.setTitle(prevTitle);
            map.put("prev", prevArticle);
        }
        //下一篇数据
        int nextId = ArticleId + 1;
        //LambdaQueryWrapper<YddArticle>wrapperNext=new LambdaQueryWrapper<>();
        YddArticle nextById = getById(nextId);
        if (nextById==null){
            map.put("next", null);
        }else {
            String nextTitle = nextById.getTitle();
            nextArticle.setId(nextId);
            nextArticle.setTitle(nextTitle);
            map.put("next", nextArticle);
        }

        //文章详情数据
        Map<Object, Object> infoMap = new HashMap<>();
        YddArticle yddArticle = getById(ArticleId);
        Integer cateid = yddArticle.getCateid();
        YddCate yddCate = iYddCateService.getById(cateid);
        String catename = yddCate.getCatename();
        infoMap.put("catename", catename);
        infoMap.put("id", yddArticle.getId());
        infoMap.put("title", yddArticle.getTitle());
        infoMap.put("author", yddArticle.getAuthor());
        infoMap.put("keywords", yddArticle.getKeywords());
        infoMap.put("description", yddArticle.getDescription());
        infoMap.put("content", yddArticle.getContent());
        infoMap.put("pic", yddArticle.getPic());
        infoMap.put("ishot", yddArticle.getIshot());
        infoMap.put("istop", yddArticle.getIstop());
        infoMap.put("create_date", yddArticle.getCreateDate());
        infoMap.put("update_date", yddArticle.getUpdateDate());
        infoMap.put("cateid", yddArticle.getCateid());
        infoMap.put("tags", yddArticle.getTags());
        infoMap.put("status", yddArticle.getStatus());
        infoMap.put("lovenum", yddArticle.getLovenum());
        infoMap.put("user_id", yddArticle.getUserId());
        map.put("info", infoMap);
        //推荐文章数据
        Integer ishot = 1;
        wrapper.eq(YddArticle::getIshot, 1);
        List<YddArticle> list = list(wrapper);
        map.put("recommend", list);
        return ResultData.ok("操作成功", map);
    }


    /*@Override
    public ResultData pageMyArticle(String limit, String page) {


        Page<YddArticle> yddArticlePage = new Page<>(Long.valueOf(page), Long.valueOf(limit));
        //构建搜索条件 - name进行模糊匹配
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();

//构建排序条件 - 更新时间倒序排序
        wrapper.orderByDesc(YddArticle::getUpdateDate);
        wrapper.eq(YddArticle::getDefaultData, 1);

        Page<YddArticle> page2 = page(yddArticlePage, wrapper);
        //执行分页查询
        HashMap<Object, Object> map = new HashMap<>();
        map.put("pageSize", page2.getSize());
        map.put("currentPage", page2.getCurrent());
        map.put("data", page2.getRecords());
        map.put("count", page2.getTotal());
        return ResultData.ok("查询成功", map);*/
    /* }
     */

    @Override
//查询首页大列表
    public ResultData findPage(String page, String limit) {
        Page<YddArticle> yddArticlePage = new Page<>(Integer.valueOf(page), Integer.valueOf(limit));
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        Date date = new Date();
        //获取当前时间的毫秒值
        long endTime = date.getTime();
        long starTime = endTime - 7 * 24 * 60 * 60 * 1000;
        queryWrapper.gt(YddArticle::getCreateDate, starTime);
        queryWrapper.le(YddArticle::getCreateDate, endTime);
        queryWrapper.orderByDesc(YddArticle::getUpdateDate);
        queryWrapper.orderByDesc(YddArticle::getUpdateDate);
        page(yddArticlePage, queryWrapper);

        Page<YddArticleDto> yddArticleDaoPage = new Page<>();
        BeanUtils.copyProperties(yddArticlePage, yddArticleDaoPage, "records");
        //获取记录
        List<YddArticle> records = yddArticlePage.getRecords();
        //相当于遍历,item代表每一个Setmeal
        List<YddArticleDto> collect = records.stream().map((item) -> {
            //获取分类id,根据id获取分类名称
            YddArticleDto yddArticleDao = new YddArticleDto();
            BeanUtils.copyProperties(item, yddArticleDao);
            Integer cateid = item.getCateid();
            YddCate cate = iYddCateService.getById(cateid);

            if (ObjectUtil.isNotNull(cate)) {
                String catename = cate.getCatename();
                //目前setmealDto中只有oryName属性,其他均为null,还需要拷贝其他属性
                yddArticleDao.setCatename(catename);
                yddArticleDao.setIstop(1);
                yddArticleDao.setIshot(1);
            }
            //根据id获取分类名称
            return yddArticleDao;
            //流闭合处理
        }).collect(Collectors.toList());
//封装分页列表数据
        yddArticleDaoPage.setRecords(collect);
        int num_week = Integer.parseInt(String.valueOf(yddArticleDaoPage.getTotal()));

        HashMap<Object, Object> map1 = new HashMap<>();
        map1.put("count",   Convert.toInt(yddArticleDaoPage.getTotal()));
        map1.put("totalPages",  Convert.toInt(yddArticleDaoPage.getPages()));
        map1.put("pageSize", Convert.toInt(yddArticleDaoPage.getSize()));
        map1.put("currentPage", Convert.toInt(yddArticleDaoPage.getCurrent()));
        map1.put("data", yddArticleDaoPage.getRecords());
        //查询24小时最新
        LambdaQueryWrapper<YddArticle> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.gt(YddArticle::getCreateDate, endTime - 24 * 60 * 60 * 1000);
        queryWrapper1.le(YddArticle::getCreateDate, endTime);
        queryWrapper1.orderByDesc(YddArticle::getUpdateDate);

        List<YddArticle> listArticle = list(queryWrapper1);
        int num_day = listArticle.size();

        HashMap<Object, Object> map = new HashMap<>();
        map.put("desc", "首页大列表");
        map.put("num_day", num_day);
        map.put("num_week", num_week);
        map.put("list", map1);

        return ResultData.ok("查询成功", map);

    }

    @Override
    public ResultData findArticleList(String page, String limit, String cateid) {
        Page<YddArticle> yddArticlePage = new Page<>(Integer.valueOf(page), Integer.valueOf(limit));


        Page<YddArticleDto> yddArticleDaoPage = new Page<>();
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(YddArticle::getUpdateDate);
        wrapper.eq(YddArticle::getCateid,cateid);
        page(yddArticlePage, wrapper);
        BeanUtils.copyProperties(yddArticlePage, yddArticleDaoPage, "records");
        //获取记录
        List<YddArticle> records = yddArticlePage.getRecords();
        //相当于遍历,item代表每一个Setmeal
        List<YddArticleDto> collect = records.stream().map((item) -> {
            //获取分类id,根据id获取分类名称
            YddArticleDto yddArticleDao = new YddArticleDto();
            BeanUtils.copyProperties(item, yddArticleDao);
            YddCate cate = iYddCateService.getById(Integer.valueOf(cateid));

            if (ObjectUtil.isNotNull(cate)) {
                String catename = cate.getCatename();
                //还需要拷贝其他属性
                yddArticleDao.setCatename(catename);
            }
            //根据id获取分类名称
            return yddArticleDao;
            //流闭合处理
        }).collect(Collectors.toList());
        //封装分页列表数据
        yddArticleDaoPage.setRecords(collect);

        HashMap<Object, Object> map1 = new HashMap<>();
        map1.put("count", yddArticleDaoPage.getTotal());
        map1.put("totalPages", yddArticleDaoPage.getPages());
        map1.put("pageSize", yddArticleDaoPage.getSize());
        map1.put("currentPage", yddArticleDaoPage.getCurrent());
        map1.put("data", yddArticleDaoPage.getRecords());

        HashMap<Object, Object> map = new HashMap<>();
        map.put("list", map1);
        return ResultData.ok("查询成功", map);
    }

    @Override
    public ResultData findHot() {

        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
   /* Date date = new Date();
    //获取当前时间的毫秒值
    long endTime = date.getTime();
    long starTime = endTime - 7 * 24 * 60 * 60 * 1000;
    queryWrapper.gt(YddArticle::getCreateDate, starTime);
    queryWrapper.le(YddArticle::getCreateDate, endTime);*/
        queryWrapper.orderByDesc(YddArticle::getClick);
        List<YddArticle> list1 = list(queryWrapper);

        //相当于遍历
        List<YddArticleDto> list = list1.stream().map((item) -> {
            //获取分类id,根据id获取分类名称
            YddArticleDto yddArticleDao = new YddArticleDto();
            BeanUtils.copyProperties(item, yddArticleDao);
            Integer cateid = item.getCateid();
            YddCate cate = iYddCateService.getById(cateid);

            if (ObjectUtil.isNotNull(cate)) {
                String catename = cate.getCatename();
                //目前setmealDto中只有oryName属性,其他均为null,还需要拷贝其他属性
                yddArticleDao.setCatename(catename);
            }
            //根据id获取分类名称
            return yddArticleDao;
            //流闭合处理
        }).limit(10).collect(Collectors.toList());
        HashMap<Object, Object> map = new HashMap<>();

        map.put("desc", "侧边最新文章");
        map.put("list", list);

        return ResultData.ok("查询成功", map);
    }

    @Override
    public ResultData findRecommend() {
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
   /* Date date = new Date();
    //获取当前时间的毫秒值
    long endTime = date.getTime();
    long starTime = endTime - 7 * 24 * 60 * 60 * 1000;
    queryWrapper.gt(YddArticle::getCreateDate, starTime);
    queryWrapper.le(YddArticle::getCreateDate, endTime);*/
        queryWrapper.orderByDesc(YddArticle::getLovenum);


        List<YddArticle> list1 = list(queryWrapper);

        //相当于遍历
        List<YddArticleDto> list = list1.stream().map((item) -> {
            //获取分类id,根据id获取分类名称
            YddArticleDto yddArticleDao = new YddArticleDto();
            BeanUtils.copyProperties(item, yddArticleDao);
            Integer cateid = item.getCateid();
            YddCate cate = iYddCateService.getById(cateid);

            if (ObjectUtil.isNotNull(cate)) {
                String catename = cate.getCatename();
                //目前setmealDto中只有oryName属性,其他均为null,还需要拷贝其他属性
                yddArticleDao.setCatename(catename);
            }
            //根据id获取分类名称
            return yddArticleDao;
            //流闭合处理
        }).collect(Collectors.toList());
        HashMap<Object, Object> map = new HashMap<>();
        map.put("desc", "侧边推荐文章");
        map.put("list", list);
        return ResultData.ok("查询成功", map);
    }

}
